package com.example.demo.controller;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/file")
public class FileController {
	private final static String FILE_PATH = "D://data/";

	@RequestMapping("/upload")
	public String upload(@RequestParam("file") MultipartFile file, @RequestParam("file2") MultipartFile file2,
			HttpServletRequest request) throws IOException {
		if (!file.isEmpty()) {
			String fileName = file.getOriginalFilename();
			System.out.println("文件名： " + fileName);
			String suffixName = fileName.substring(fileName.lastIndexOf("."));
			System.out.println("文件后缀名： " + suffixName);
			// 重新生成唯一文件名
			String newFileName = UUID.randomUUID().toString() + suffixName;
			System.out.println("新的文件名： " + newFileName);
			// 创建文件
			byte[] bytes = file.getBytes();
			Path path = Paths.get(FILE_PATH + newFileName);
			Files.write(path, bytes);
		}
		if (!file2.isEmpty()) {
			String fileName = file2.getOriginalFilename();
			System.out.println("文件名： " + fileName);
			String suffixName = fileName.substring(fileName.lastIndexOf("."));
			System.out.println("文件后缀名： " + suffixName);
			// 重新生成唯一文件名
			String newFileName = UUID.randomUUID().toString() + suffixName;
			System.out.println("新的文件名： " + newFileName);
			// 创建文件
			byte[] bytes = file2.getBytes();
			Path path = Paths.get(FILE_PATH + newFileName);
			Files.write(path, bytes);
		}
		return "success";
	}
}
